//
//  PhotosUploadManager.m
//  Scanner
//
//  Created by apple on 15-5-16.
//  Copyright (c) 2015年 米明. All rights reserved.
//

#import "PhotosUploadManager.h"

static PhotosUploadManager * manager=nil;
@implementation PhotosUploadManager
{
    void (^_callBack)(BOOL succeed);
    NSTimer * _timer;
    UploadTask * _uploadingTask;//上传中的Task
    
}
-(void)stopRun{
    [_timer setFireDate:[NSDate distantFuture]];
    self.running = NO;
}

-(void)startRun{
    [_timer setFireDate:[NSDate distantPast]];
    self.running = YES;
}
+(PhotosUploadManager *)manager{
    if (manager==nil) {
        manager = [[PhotosUploadManager alloc]init];
    }
    return manager;
}

-(instancetype)init{
    self=[super init];
    if (self) {
        [self setup];
    }
    return self;
}

-(void)deletePhotoWithGoodsId:(NSString *)goodsId uri:(NSString *)uri callBack:(void (^)(BOOL succeed))callBack{
    
    _callBack=nil;
    
    _callBack=[callBack copy];
    
    NSString * url=Delete_Url;
    
    NSDictionary * parDict=[NSDictionary dictionaryWithObjectsAndKeys:goodsId,@"id",uri,@"uri", nil];
    
    //使用Post请求把新用户信息写入应用服务器数据库
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    
    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html", nil];
    
  //  NSLog(@"^^^^ %@",parDict);
    
    [manager GET:url parameters:parDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
      //  NSLog(@"RESPONSE %@",responseObject);
        if ([responseObject[RETURN_RET] intValue]==1) {
            _callBack(YES);
        }else{
            _callBack(NO);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //   NSLog(@"Error %@",error);
        _callBack(NO);
    }];
}
-(void)clean{
    self.succeedTasks=[[NSMutableDictionary alloc]init];
    [self readFromLoc];
}
-(void)setup{
    
    self.tasks = [[NSMutableDictionary alloc]init];
    
  //  self.succeedTasks=[[NSMutableDictionary alloc]init];
    
    [self readFromLoc];
    
    //妙
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkUpTask) userInfo:nil repeats:YES];
}
-(void)readFromLoc{
    
    NSMutableArray * tasks=[[CoreDataManager shareManager]tasks];
    
    for (UploadTask * task in tasks) {
        [self.tasks setObject:task forKey:task.photoPath];
    }
    
    NSLog(@"loc tasks %@",self.tasks);
    
}
-(void)checkUpTask{
   // NSLog(@"checking");
    
    self.running = YES;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (_uploadingTask == nil) {//如果没有任务 让第一个任务执行
            if (self.tasks.allKeys.count<=0) {
                return;
            }
            
            if ([self getOrderTasks]) {
                _uploadingTask = [[self getOrderTasks] firstObject];
                [_uploadingTask startTask];
                [[CoreDataManager shareManager]addGoods:_uploadingTask.goods];
            }
            
        }//否则监测 是否已经执行完毕 执行完毕 置为nil
        else{
            if (_uploadingTask.succeed) {
                [self removeTask:_uploadingTask];
                _uploadingTask=nil;
            }else{
                NSLog(@"shibai");
                [self.tasks removeObjectForKey:_uploadingTask.photoPath];
                UIImage * photo = [UIImage imageWithContentsOfFile:_uploadingTask.photoPath];
                if (photo.size.width<=0) {
                    [[CoreDataManager shareManager]deleteTaskByPhotoPath:_uploadingTask.photoPath];
                }
     
                _uploadingTask=nil;
            }
        }
    });
}
//未完成的任务所有的key
-(NSArray *)allTaskPhotoPaths{
    return self.tasks.allKeys;
}
-(NSArray *)allTasks{
    return self.tasks.allValues;
}
//有序的任务
-(NSMutableArray *)getOrderTasks{

    //序号
    NSMutableArray * numbers=[[NSMutableArray alloc]init];
    
    for (UploadTask * task  in [self allTasks]) {
        [numbers addObject:@(task.number)];
    }
    
    //所有序号升序
    
    for (int i=0; i<numbers.count-1; i++) {
        
        for (int j=0; j<numbers.count-1-i; j++) {
            
            if ([numbers[j] integerValue] > [numbers[j+1] integerValue]) {
                [numbers exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }

        }
    }
    
    NSMutableArray * tasks=[[NSMutableArray alloc]init];
    
    for (int i=0; i<numbers.count; i++) {
        for (UploadTask * task  in [self allTasks]) {
            if (task.number ==[numbers[i] integerValue]) {
                [tasks addObject:task];
            }
        }
    }
   // NSLog(@"%@",numbers);
    
    return tasks;
}

-(void)addOneTask:(UploadTask *)task{
    [_tasks setObject:task forKey:task.photoPath];
    [[CoreDataManager shareManager]addTask:task];
}

-(void)removeTask:(UploadTask *)task{
    
    [_tasks removeObjectForKey:task.photoPath];

//    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//    
//    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"/"];
    
    
    NSFileManager * fileManage = [NSFileManager defaultManager];
    //先判断这个文件夹是否存在，如果不存在则创建，否则不创建
    if ([fileManage fileExistsAtPath:task.photoPath]) {
        NSLog(@"存在");
        if([fileManage removeItemAtPath:task.photoPath error:nil]){
            
        }
    }
    
    [[CoreDataManager shareManager]deleteTaskByPhotoPath:task.photoPath];

}


-(UploadTask *)creatOneTaskWithPhoto:(UIImage *)photo goods:(Goods *)goods{
    UploadTask * task=[[UploadTask alloc]initWithPhoto:photo goods:goods];
    [self addOneTask:task];
    return task;
}
-(UploadTask *)creatOneTaskWithPhotoPath:(NSString *)photoPath goods:(Goods *)goods{
    
    UploadTask * task=[[UploadTask alloc]initWithPhotoPath:photoPath goods:goods];
    [self addOneTask:task];
    return task;
}



@end
